//
//  SecondViewController.m
//  testTimer
//
//  Created by Feng on 2021/9/9.
//

#import "SecondViewController.h"

#define WEAKSELF typeof(self) __weak weakSelf = self;
#define STRONGSELF typeof(weakSelf) __strong strongSelf = weakSelf;

@interface SecondViewController ()

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//  ios10之后：官方推荐方案
    WEAKSELF
    self.timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        STRONGSELF //避免block循环引用
        [strongSelf timerAction];
    }];
//  ios10之前：（NSTimer+weak loading的时候交换了方法）
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

-(void)viewWillAppear:(BOOL)animated {
    if (self.timer) {
        [self.timer setFireDate:[NSDate distantPast]];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    if (self.timer) {
        [self.timer setFireDate:[NSDate distantFuture]];
    }
}

- (void)dealloc {
    if (self.timer) {
        [self.timer invalidate]; //dealloc时候从runloop中删除timer
        self.timer = nil;
    }
    NSLog(@"Feng SecondViewController dealloc");
}

-(void)timerAction {
    NSLog(@"Feng timer test");
}
@end
